import { merge } from "./index";

let LOADER_INDEX = 0;
export default options => {
    let opt = {
        url: "",
        proxy: "",
        method: "GET",
        data: {},
        loader: true,
        headers: {},
    };
    opt = merge(true, opt, options);
    opt.method = opt.method.toUpperCase();
    requestHandler(opt);
    // console.log("requestOptions", opt);
    return new Promise((resolve, reject) => {
        wx.request({
            method: opt.method,
            url: opt.url,
            data: opt.data,
            timeout: 30000,
            dataType: "json",
            header: {
                ...opt.headers,
            },
            success(res) {
                // console.log("success", res);
                responseHandler(res, opt, resolve, reject);
            },
            fail(res) {
                // console.log('fail',res);
                responseHandler(res, opt, resolve, reject);
            },
        });
    }).catch(error => {
        wx.askShowToastEx({
            mask: true,
            title: error.msg || error.message,
            icon: "none",
            duration: 2000,
            cancel: () => {
                if (error.error && error.error.statusCode === 401) {
                    opt.complete && opt.complete(error);
                }
            },
        });
        throw error;
    });
};

const requestHandler = opt => {
    if (opt.loader) {
        wxLoader(true);
    }
};
const responseHandler = async (res, opt, resolve, reject) => {
    if (opt.loader) {
        await wxLoader(false);
    }
    if (
        res === void 0 ||
        (res.message && res.message.indexOf("Network") !== -1 && res.message.indexOf("Error") !== -1)
    ) {
        // console.log('服务器地址不存在！');
        res.msgInfo = "服务器地址不存在";
        return reject({
            message: res.msgInfo,
            error: res,
        });
    }
    if (res.statusCode === 200) {
        return resolve(res);
    }
    if (res.errMsg && res.errMsg.indexOf("timeout") !== -1) {
        res.msgInfo = "接口请求超时";
        return reject({
            message: res.msgInfo,
            error: res,
        });
    }
    const _status = res.statusCode;
    switch (_status) {
        case 400:
            res.msgInfo = "错误的请求";
            break;
        case 403:
            res.msgInfo = "拒绝访问";
            break;
        case 404:
            res.msgInfo = `错误的地址: ${opt.url}`;
            break;
        case 401:
            res.msgInfo = `登录过期`;
            break;
        case 408:
            res.msgInfo = "请求超时";
            break;
        case 500:
        case 501:
        case 502:
        case 503:
        case 504:
        case 505:
            res.msgInfo = "服务器错误";
            break;
        default:
            res.msgInfo = "接口请求失败";
            break;
    }
    return reject({
        message: res.msgInfo,
        error: res,
    });
};

const wxLoader = loader =>
    new Promise(resolve => {
        if (loader) {
            if (LOADER_INDEX === 0) {
                wx.showLoading({
                    title: "加载中",
                    mask: true,
                });
            }
            LOADER_INDEX++;
            resolve();
        }
        if (!loader) {
            LOADER_INDEX--;
            if (LOADER_INDEX === 0) {
                setTimeout(() => {
                    LOADER_INDEX === 0 && wx.hideLoading();
                    wx.nextTick(() => {
                        resolve();
                    });
                }, 2000);
            } else {
                resolve();
            }
        }
    });
